<script setup>
import { onMounted, reactive, ref,watch } from "vue";
import { reportService } from "@/api/hospital";
import { useRoute } from "vue-router";
import { ElMessage, ElNotification } from "element-plus";
import { archieveRepostService, saveRepostService } from "@/api/report";
import router from "@/router/index.js";
import {user} from "@/stores/counter.js";
const curUser = user()
const changed=ref(false);
// 报告信息模板
const report = ref({
  items: [
    {
      ciId: "",
      ciname: "",
      cicontent: "",
      meaning: "",
      remarks: "",
      items: [
        {
          cidrid: "",
          name: "",
          unit: "",
          minrange: "",
          maxrange: "",
          normalvalue: "",
          normalvaluestring: "",
          type: "",
          value: "",
          iserror: "",
          ciid: "",
          orderid: 100569823,
        },
      ],
    },
  ],
  results: [
    {
      orid: "",
      title: "",
      content: "",
      orderid: null,
    },
    {
      orid: "",
      title: "",
      content: "",
      orderid: null,
    },
  ],
});
const route = useRoute();
const canchange = ref(false);
watch(  
  () => report,  
  () => {  
    changed.value=true;
   // console.log("changed");

  },  
  { deep: true }  
); 
// 初始化
onMounted(() => {
  setDeafutl();
  fetchDate();
});

// 获取报告信息
const fetchDate = async () => {
  await reportService(patientInfo.orderId).then((res) => {
    console.log(res);
    report.value = res.data;
    summaryItems.splice(0, summaryItems.length);
    res.data.results.forEach((item) => {
      summaryItems.push(item);
    });
  });
};

const isUpdating = ref(false);

// 保存功能
const save = async () => {
  isUpdating.value = true;
  report.value.results = summaryItems;
  let results = await saveRepostService(report.value);
  isUpdating.value = false;
  if (results.code === 200) {
    ElMessage.success("保存成功!");
    location.reload();
  } else {
    ElMessage.error(results.message);
  }
};

// 归档功能
const archive = async () => {
  isUpdating.value = true;
  report.value.results = summaryItems;
  let results = await archieveRepostService(report.value);
  isUpdating.value = false;
  if (results.code === 200) {
    canchange.value = true;
    ElMessage.success("归档成功!");
    router.push("/home");
  } else {
    ElMessage.error(results.message);
  }
};

const change = (index1, index2, item) => {
  console.log(report.value.items[index1]);
  console.log(item.value);
  console.log(index1, index2);
  if (item.minrange !== null && item.maxrange !== null) {
    if (item.value >= item.minrange && item.value <= item.maxrange) {
      report.value.items[index1].items[index2].iserror = 0;
      console.log("ok");
    } else {
      console.log("error");
      report.value.items[index1].items[index2].iserror = 1;
    }
  }
};

const readOnly = ref(false);

// 路由传参获取信息
const setDeafutl = () => {
  patientInfo.orderId = route.query.orderid;
  patientInfo.phone = route.query.phone;
  patientInfo.realName = route.query.realName;
  patientInfo.sex = route.query.sex;
  patientInfo.type = route.query.type;
  patientInfo.date = route.query.orderdate;
  readOnly.value = Number(route.query.state) !== 3;
  if (readOnly.value) {
    ElNotification({
      title: "注意",
      message: "当前处于只读状态",
      duration: 4500,
    });
  }
};

// 患者信息
const patientInfo = reactive({
  orderId: "",
  phone: "",
  realName: "",
  sex: "",
  type: "",
  date: "",
});

// 总检结论项目
const summaryItems = reactive([
  {
    orderId: null,
    orid: null,
    title: "",
    content: "",
  },
]);

// 总检结论标题
const summaryTitle = ref("");

// 总检结论内容
const summaryContent = ref("");

// 插入结论
const insertSummary = (row) => {
  if (summaryTitle.value === "" || summaryContent.value === "") {
    ElMessage.error("输入不能为空!");
  } else {
    summaryItems.push({
      orid: null,
      title: summaryTitle.value,
      content: summaryContent.value,
      orderid: patientInfo.orderId,
    });
    summaryTitle.value = "";
    summaryContent.value = "";
  }
};

// 更新结论
const updateSummary = (row) => {
  console.log("selected",row);
  // 搜索符合条件的结论
  const targetItem = summaryItems.find(
    (item) => item.title === row.title && item.content === row.content
  );
  // 进行修改
  if (targetItem) {
    let tmp = prompt("请输入修改后的标题");
    if (tmp) targetItem.title = tmp;
    tmp = prompt("请输入修改后的内容");
    if (tmp) targetItem.content = tmp;
  }
};

// 删除结论
const deleteSummary = (row) => {
  const index = summaryItems.findIndex(
    (item) => item.title === row.title && item.content === row.content
  );
  if (index !== -1) {
    summaryItems.splice(index, 1);
  }
};
</script>

<template>
  <div class="wrapper">
    <el-container v-loading="isUpdating">
      <!-- 头部 -->
      <el-header class="hop-header">
        <el-page-header :icon="ArrowLeft" @click="router.push('/home')">
          <template #title>
            <span style="font-size: larger"> 返回 </span>
          </template>
          <template #content>
            <div
              style="
                display: flex;
                flex-direction: row;
                align-items: center;
                text-align: center;
                justify-content: center;
              "
            >
              <img
                src="../assets/img/qiqi2.png"
                style="width: 30px;margin: 0 5px;padding-top: 5px"
                alt="op"
              />
              <span style="font-size: larger">
                不卜庐养生堂体检报告管理系统
              </span>
            </div>
          </template>
        </el-page-header>
        <div style="display: flex; flex-direction: row; align-items: center">
          <div
            style="
              color: #333f29;
              font-weight: normal;
              font-size: medium;
              margin: 0 10px 4px;
            "
          >
            医生：孙思邈
          </div>
          <el-divider direction="vertical" />
          <el-button text  @click="curUser.logout().then(()=>{ElMessage.success('登出成功');router.push('/login')})">退出登录</el-button>
        </div>
      </el-header>
      <el-container>
        <!-- 侧边栏 -->
        <el-aside class="hop-aside">
<!--          <div-->
<!--            style="-->
<!--              font-weight: bold;-->
<!--              color: #4b545d;-->
<!--              padding: 15px;-->
<!--              font-size: larger;-->
<!--            "-->
<!--          >-->
<!--            预约用户查询-->
<!--          </div>-->
<!--          <table class="info-table">-->
<!--            <tr>-->
<!--              <th>预约编号</th>-->
<!--              <td>{{ patientInfo.orderId }}</td>-->
<!--            </tr>-->
<!--            <tr>-->
<!--              <th>手机号码</th>-->
<!--              <td>{{ patientInfo.phone }}</td>-->
<!--            </tr>-->
<!--            <tr>-->
<!--              <th>真实姓名</th>-->
<!--              <td>{{ patientInfo.realName }}</td>-->
<!--            </tr>-->
<!--            <tr>-->
<!--              <th>性别</th>-->
<!--              <td>{{ patientInfo.sex }}</td>-->
<!--            </tr>-->
<!--            <tr>-->
<!--              <th>套餐类型</th>-->
<!--              <td>{{ patientInfo.type }}</td>-->
<!--            </tr>-->
<!--            <tr>-->
<!--              <th>体检日期</th>-->
<!--              <td>{{ patientInfo.date }}</td>-->
<!--            </tr>-->
<!--          </table>-->

          <el-descriptions
              class="user-info-descriptions"
              title="用户信息"
              :column="1"
              direction="vertical"
              border
              size="default"
          >
            <el-descriptions-item label="预约编号">{{patientInfo.orderId}}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">{{patientInfo.realName}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{patientInfo.sex}}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{patientInfo.phone}}</el-descriptions-item>
            <el-descriptions-item label="套餐类型">
              <el-tag type="success" size="small">{{ patientInfo.type}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="体检日期">{{patientInfo.date}}</el-descriptions-item>
          </el-descriptions>
        </el-aside>

        <el-main class="hop-main">
          <el-collapse>
            <el-collapse-item
              :title="item.ciname"
              :name="index"
              v-for="(item, index1) in report.items"
              :key="index1"
            >
              <div class="physicalExaminationItemContainer">
                <div
                  class="physicalExaminationItem"
                  v-for="(itemss, index2) in item.items"
                  :key="index2"
                >
                  <div class="abnormal" v-if="itemss.iserror === 1">异</div>
                  <div>{{ itemss.name }}</div>
                  <el-input
                    v-model="itemss.value"
                    style="width: auto; padding: 10px"
                    @input="change(index1, index2, itemss)"
                    :disabled="canchange || readOnly"
                  ></el-input>
                  <div>{{ itemss.unit }}</div>
                  <div>
                    正常值范围：{{ itemss.minrange }}-{{ itemss.maxrange }}
                  </div>
                </div>
              </div>
              <el-button :disabled="readOnly" type="primary" @click="save()">
                {{ item.ciname }}项保存</el-button
              >
            </el-collapse-item>
          </el-collapse>

          <div class="summaryForm">
            <!-- 总检结论导航 -->
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px;
              "
            >
              <div
                style="
                  color: #555b5e;
                  font-size: larger;
                  margin-top: 10px;
                  margin-left: 10px;
                "
              >
                总检结论
              </div>
              <div>
                <el-button :disabled="readOnly" type="primary" @click="save"
                  >保存</el-button
                >
                <el-button :disabled="readOnly" type="danger" @click="archive"
                  >体检套餐总检结果报告归档</el-button
                >
              </div>
            </div>
            <el-divider />
            <!-- 总检结论表格 -->
            <el-table :data="summaryItems" style="width: 100%">
              <el-table-column
                prop="orid"
                label="编号"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="title"
                label="总检结论项标题"
              ></el-table-column>
              <el-table-column
                prop="content"
                label="总检结论项内容"
              ></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button
                    type="text"
                    size="small"
                    :disabled="readOnly"
                    @click="
                      () => {
                        updateSummary(scope.row);
                      }
                    "
                    >更新</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    :disabled="readOnly"
                    @click="
                      () => {
                        deleteSummary(scope.row);
                      }
                    "
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 总检结论添加按钮 -->
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px;
              "
            >
              <div style="width: 150px; color: #555b5e; margin-left: 10px">
                总检结论项标题
              </div>
              <el-input v-model="summaryTitle" placeholder="请输入" />
            </div>
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px;
              "
            >
              <div style="width: 150px; color: #555b5e; margin-left: 10px">
                总检结论项内容
              </div>
              <el-input
                v-model="summaryContent"
                placeholder="请输入"
                :rows="2"
                type="textarea"
              />
            </div>
            <el-button
              type="primary"
              :disabled="readOnly"
              style="margin: 20px"
              @click="insertSummary"
              >添加总检结论</el-button
            >
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>

body {
  /* 隐藏页面内容，直到动画开始 */
  overflow: hidden;
}

.wrapper {
  animation: slideInFromLeft 500ms ease forwards; /* 添加动画 */
}

@keyframes slideInFromLeft {
  0% {
    transform: translateX(100%); /* 初始状态：位于左侧屏幕外 */
    opacity: 0;
  }
  100% {
    transform: translateX(0); /* 最终状态：回到原始位置 */
    opacity: 1;
  }
}


.hop-header {
  background-color: #f7f7f7;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  height: 8vh;
}

.hop-aside {
  background-color: #f7f7f7;
  height: 100vh;
}

.hop-main {
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.info-table {
  border-collapse: collapse;
  margin: 20px;
  padding: 10px;
  box-shadow: 2px 2px 5px rgba(204, 204, 204, 0.5);
  font-family: "Microsoft YaHei";
  border-radius: 5%;
}

.info-table th,
.info-table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

.info-table th {
  background-color: #FFFFFF;
  font-weight: normal;
  width: 100px;
  font-size: small;
}

.info-table td {
  font-size: small;
  background-color: #FFFFFF;
  width: 200px;
}

.physicalExaminationItemContainer {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
}

.physicalExaminationItem {
  flex: 0 0 calc(50% - 10px); /* 每个项目占据50% - 间距 */
  margin: 5px; /* 间距 */

  box-sizing: border-box; /* 边框计算在宽度内 */
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.summaryForm {
  box-shadow: rgba(0, 0, 0, 0.4) 0px 0px 3px;
  border-radius: 15px;
  margin-top: 25px;
}

.abnormal {
  width: 20px;
  height: 20px;
  text-align: center;
  background-color: #b5654e;
  color: #ffffff;
  border-radius: 25%;
  margin: 5px;
}

.itemContainer {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.user-info-descriptions{
  border-radius: 1%;
  margin: 15px;
  margin-top: 0px;
  background-color: #FFFFFF;
  padding: 10px;
  box-shadow: 2px 2px 5px rgba(204, 204, 204, 0.5);
  font-family: "Microsoft YaHei";
}
</style>